import React from 'react'
import type { FormProps } from 'antd';
import { Button, Form, Input, message } from 'antd';
import { request } from '../../utils/request';
import './styleLogin.css'
import { useNavigate } from 'react-router-dom';
import { setToken } from '../../utils/token';

function Login() {
  // 定义表单字段类型
  type FieldType = {
    username?: string;
    password?: string;
    remember?: string;
  };
  // 使用message组件
  const [messageApi, contextHolder] = message.useMessage();
  // 使用useNavigate钩子函数
  const navigate = useNavigate()
  //登录请求
  const onFinish: FormProps<FieldType>['onFinish'] = async (values) => {
    //账号:haha12  密码:123456
    console.log('Success:', values);
    // 发送登录请求
    const res = await request.post('/login', values)
    console.log('登录', res)

    //判断
    if (res.code === 10000) {
      //存储token
      setToken(res.data.accessToken)
      //存储refreshToken 
      localStorage.setItem('refreshToken', res.data.refreshToken)
      //成功登录
      messageApi.open({
        type: 'success',
        content: res.message,
      });
      //跳转到首页
      setTimeout(() => {
        navigate('/home')
      }, 1000)

    }

  };
  // 登录失败
  const onFinishFailed: FormProps<FieldType>['onFinishFailed'] = (errorInfo) => {
    console.log('Failed:', errorInfo);
  };
  return (

    <div className='login'>
      {contextHolder}
      <div className="login-page">


        <div className='login-form'>

          <Form

            name="basic"
            labelCol={{ span: 8 }}
            wrapperCol={{ span: 16 }}
            style={{ maxWidth: 600 }}
            initialValues={{ remember: true }}
            onFinish={onFinish}
            onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item<FieldType>
              label="用户名"
              name="username"
              rules={[{ required: true, message: '请输入用户名!' }]}
            >
              <Input />
            </Form.Item>

            <Form.Item<FieldType>
              label="密码"
              name="password"
              rules={[{ required: true, message: '请输入密码!' }]}
            >
              <Input.Password />
            </Form.Item>



            <Form.Item label={null}>
              <Button type="primary" htmlType="submit">
                登录
              </Button>
            </Form.Item>
          </Form>
        </div>
      </div>


    </div>
  )
}

export default Login
